import Imagelocation from '@/components/Imagelocation';
import pRightGray from '@/images/common/rightGray.svg';
import pZhekou from '@/images/common/zhekou.png';
import pCheaper from '@/images/taihuHomePage/cheaper.png';
import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useRef } from 'react';
import { connect } from 'react-redux';
import { getValidDate } from '../../dataTransfer/coupon';
import Advert from '../../pages/advert';
import ListEnd from '../giftCardDetail/listEnd';
import pHot from '../images/activity/hot.png';
import pSale from '../images/activity/sale.png';
import './index.scss';

const ActivityType = {
  // 满减
  rebate: 2,
  // 折扣
  off: 3,
};

// 满减 单个商品
const RebateOne = ({ activityName, fullReduces, product, disabled, goToBuy }) => {
  const rebateInfo = fullReduces
    .map((v) => {
      return v.match(/\d+(\.\d+)?/g);
    })
    .sort(([v1], [v2]) => {
      return +v1 < +v2;
    })[0];

  return (
    <View className={classNames('activity-item card-item', { disabled })}>
      <View className="left">
        <Imagelocation className="product-img" src={product.url} />
      </View>
      <View className="right">
        <View className="info">
          <View className="name">{activityName}</View>
          <View className="intro">{product.title}</View>
          <View className="pricePay">
            <View className="realPrice">
              <Text className="unit">￥</Text>
              <Text className="num">{product.price}</Text>
            </View>
          </View>

          <View className="coupInfo">
            <View className="coupon-wrap">
              <View className="infoBtn">
                满{rebateInfo[0]}减{rebateInfo[1]}
              </View>
            </View>
          </View>

          <View className="buyInfo">已有{product.saleNumber ?? 0}人购买</View>
        </View>
      </View>

      <View
        className={classNames('buyBtn customePageBackgroundStyle', { disabled })}
        onClick={goToBuy}
      >
        <View className="buyBtnTxt">{disabled ? '已结束' : '去抢购'}</View>
      </View>
    </View>
  );
};

// 满减多个
const RebateMulti = ({ products, fullReduces, disabled, goToBuy }) => {
  // 获取最低满减
  const rebateInfo = fullReduces
    .map((v) => {
      return v.match(/\d+(\.\d+)?/g);
    })
    .sort(([v1], [v2]) => {
      return +v1 < +v2;
    })[0];

  return (
    <View className={classNames('promote-item card-item', { disabled })}>
      <View className="top">
        <View className="left">
          <Image className="logo" src={pSale}></Image>
        </View>
        <View className="coupon-info">
          <View className="left-txt">
            <View className="txt-value">满{rebateInfo[0]}</View>
          </View>
          <View className="right-txt">
            <View className="txt-value">减{rebateInfo[1]}</View>
          </View>
        </View>
      </View>
      <View className="center">
        <Image className="img" src={pHot}></Image>

        <View className="hot-txt">热卖中</View>
      </View>
      <View className="img-list">
        {products.slice(0, 4).map(({ url }, index) => {
          return <Imagelocation key={index} className="img-item" src={url} />;
        })}
      </View>
      <View
        className={classNames('btn-go-activity customePageBackgroundStyle', { disabled })}
        onClick={goToBuy}
      >
        <View className="btn-go-activity-txt">{disabled ? '已结束' : '参加活动'}</View>
      </View>
    </View>
  );
};

// 折扣 单个商品
const OffOne = ({ product, activityName, disabled, goToBuy }) => {
  return (
    <View className={classNames('activity-item card-item', { disabled })}>
      <View className="left">
        <Imagelocation className="product-img" src={product.url} />
      </View>
      <View className="right">
        <View className="info">
          <View className="name">{activityName}</View>
          <View className="intro">{product.title}</View>
          <View className="pricePay">
            <View className="realPrice">
              <Text className="unit">￥</Text>
              <Text className="num">{product.price}</Text>
            </View>

            <View className="originPrice">
              <Text className="unit">￥</Text>
              <Text className="num">{product.originalPrice}</Text>
            </View>
          </View>

          <View className="buyInfo more">已有{product.saleNumber ?? 0}人购买</View>
        </View>
      </View>

      <View
        className={classNames('buyBtn customePageBackgroundStyle', { disabled })}
        onClick={goToBuy}
      >
        <View className="buyBtnTxt">{disabled ? '已结束' : '去抢购'}</View>
      </View>
    </View>
  );
};

const OffMulti = ({ products, disabled, goToBuy }) => {
  return (
    <View onClick={goToBuy} className={classNames('cheaperArea card-item', { disabled })}>
      <View className="headerLine">
        <Image className="title" src={pCheaper} />
        <View className="more">
          <Text className="text">更多低价限时抢购</Text>
          <Image className="iconRight" src={pRightGray} />
        </View>
      </View>
      <View className={['productList', products.length < 4 && 'prolm'].join(' ')}>
        {products.length > 0 &&
          products.slice(0, 4).map((product, index) => (
            <View
              className={['product', products.length < 4 && 'prom'].join(' ')}
              key={'cheaperProduct_' + index}
            >
              <View className="upImg">
                <Imagelocation className="picture" src={product.url} />
                <Image className="activeIcon zhekou" src={pZhekou} />
              </View>
              <View className="priceLineCurrent">¥{product.price}</View>
              <View className="priceLineOrigin">¥{product.originalPrice}</View>
            </View>
          ))}
      </View>
    </View>
  );
};

const Activity = ({ dispatch, loading, activityList, activityListFinished }) => {
  useShowLoading(loading, ['giftCard/fetchActivityList']);

  // 重新渲染页面时活动列表更新
  const when = useRef(Date.now());

  // 获取 活动列表
  const getNextList = (params = { when: when.current }) => {
    return dispatch({
      type: 'giftCard/fetchActivityList',
      payload: { pageSize: 10, ...params },
    });
  };

  // 首次进入获取活动
  useDidShow(() => {
    !activityListFinished && !activityList?.length && getNextList();
  }, []);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !activityListFinished && activityList?.length > 0 && getNextList();
  }, 1200);

  return (
    <View className="ActivityToday">
      <ScrollView
        enableFlex
        scrollY
        style={{
          height: '100vh',
        }}
        onScrollToLower={handleScrollToLower}
      >
        <View className="advert">
          <Advert alias="_jrhd" goTxt="去抢购" />
        </View>

        <View className="title">热门活动</View>

        <View className="activity-list">
          {activityList?.map(
            ({
              id,
              merchantId,
              orgId,
              type,
              products,
              name,
              fullReduces,
              reduces,
              endTime,
              productSource,
            }) => {
              const disabled = getValidDate(endTime).getTime() < Date.now();
              // const disabled = false;

              const goToBuy = () => {
                if (disabled) {
                  return;
                }
                Taro.navigateTo({
                  url: `/giftCardSubPack/activityProducts/index?id=${id}&isRebate=${
                    type === ActivityType.rebate ? true : ''
                  }&merchantId=${merchantId}&orgId=${orgId}&reduces=${reduces}&productSource=${productSource}`,
                });
              };

              switch (type) {
                case ActivityType.off:
                  return products?.length === 1 ? (
                    <OffOne
                      disabled={disabled}
                      goToBuy={goToBuy}
                      activityName={name}
                      product={products[0]}
                    />
                  ) : (
                    <OffMulti
                      disabled={disabled}
                      goToBuy={goToBuy}
                      activityName={name}
                      products={products}
                    />
                  );
                case ActivityType.rebate:
                  return products?.length === 1 ? (
                    <RebateOne
                      disabled={disabled}
                      goToBuy={goToBuy}
                      activityName={name}
                      fullReduces={fullReduces}
                      product={products[0]}
                    />
                  ) : (
                    <RebateMulti
                      disabled={disabled}
                      goToBuy={goToBuy}
                      fullReduces={fullReduces}
                      products={products}
                    />
                  );
                default:
                  break;
              }
            },
          )}

          {activityListFinished && activityList?.length > 8 && <ListEnd />}
        </View>
      </ScrollView>
    </View>
  );
};

export default connect(({ giftCard, loading }) => ({
  loading,
  activityList: giftCard.activityList,
  activityListFinished: giftCard.activityListFinished,
}))(Activity);
